<!-- 计划转生产委外 -->
<template>
  <pageHeader
    title="创建产品委外"
    :breadCrumb="['工厂建模', '生产BOM管理', '创建产品委外']"
    :show-back="true"
  >
    <template #footer>
      <a-space :size="20">
        <a-button @click="router.back()">取消</a-button>
        <a-button type="primary" @click="handleOk">提交</a-button>
      </a-space>
    </template>
    <a-spin :loading="loading" class="cantainer">
      <div class="tab">生产工单信息</div>
      <div class="orderBox">
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="计划编号:">
              <a-typography-text> {{ form.list.planCode }} </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="生产订单单号:">
              <a-typography-text>
                {{ form.list.orderNumber }}
              </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="物料名称:">
              <a-typography-text>
                {{ form.list.materialName }}
              </a-typography-text>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="规格型号:">
              <a-typography-text>
                {{ form.list.materialSpec }}
              </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="产品编码:">
              <a-typography-text>
                {{ form.list.materialNumber }}
              </a-typography-text>
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item label="物料属性:">
              <a-typography-text> {{ '委外' }} </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="本周计划数量:">
              <a-typography-text>
                {{ form.list.totalNum }}
              </a-typography-text>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item label="计划日期:">
              <a-typography-text>
                {{ dayjs(form.list.startDate).format('YYYY 年 MM 月') }}
              </a-typography-text>
            </a-form-item>
          </a-col>
        </a-row>
      </div>
      <div class="tab">生产计划信息</div>
      <a-form :model="form.list" ref="formRef" auto-label-width>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="供  应  商"
              label-col-flex="100px"
            >
              <a-select
                v-model="form.list.supplierId"
                @change="getContactMan"
                :style="{ width: '320px' }"
                placeholder="请选择 ..."
              >
                <a-option
                  v-for="item in SupplierInfo"
                  :key="item.id"
                  :value="item.id"
                  >{{ item.name }}</a-option
                >
              </a-select>
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="已委外数量"
              label-col-flex="100px"
            >
              <a-input
                disabled
                :style="{ width: '320px' }"
                v-model="form.list.outsourcingAmount"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="本委外数量"
              label-col-flex="100px"
              field="amount"
              required
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                :max="form.list.totalNum - form.list.outsourcingAmount"
                v-model="form.list.amount"
                placeholder="请输入委外数量"
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="加工费(含税)"
              label-col-flex="100px"
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                v-model="form.list.unitPrice"
                placeholder="please enter..."
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              field="rate"
              label="税率"
              label-col-flex="100px"
              required
            >
              <a-input-number
                :style="{ width: '320px' }"
                v-model="form.list.rate"
                placeholder="please enter..."
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="含税合计"
              label-col-flex="100px"
            >
              <a-input-number
                :min="1"
                :style="{ width: '320px' }"
                v-model="form.list.totalPrice"
                placeholder="please enter..."
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row v-if="form.list.itemState === 1" :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货人姓名"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                v-model="form.list.consigneeName"
                placeholder="please enter..."
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货人电话"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                v-model="form.list.consigneePhone"
                placeholder="please enter..."
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货地址"
              label-col-flex="100px"
            >
              <a-input
                :style="{ width: '320px' }"
                v-model="form.list.consigneeAddress"
                placeholder="please enter..."
              />
            </a-form-item>
          </a-col>
        </a-row>
        <a-row :gutter="16">
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="委外日期"
              label-col-flex="100px"
            >
              <a-date-picker
                style="width: 330px; margin: 0 24px 24px 0"
                show-time
                :time-picker-props="{ defaultValue: '09:09:06' }"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="form.list.outsourcingDate"
              />
            </a-form-item>
          </a-col>
          <a-col :span="8">
            <a-form-item
              :show-colon="true"
              label="收货日期"
              label-col-flex="100px"
            >
              <a-date-picker
                style="width: 330px; margin: 0 24px 24px 0"
                show-time
                :time-picker-props="{ defaultValue: '09:09:06' }"
                format="YYYY-MM-DD HH:mm:ss"
                v-model="form.list.entryDate"
              />
            </a-form-item>
          </a-col>
        </a-row>
      </a-form>
      <div class="tab"
        ><a-space
          ><div>附加物料清单</div
          ><a-switch
            :checked-value="1"
            :unchecked-value="2"
            v-model="form.list.itemState"
            @change="EnableInventory"
          >
            <template #checked> ON </template>
            <template #unchecked> OFF </template>
          </a-switch></a-space
        >
      </div>
      <a-divider />
      <a-table
        :stripe="true"
        :dordered="{
          headerCell: true,
        }"
        :data="form.list.item"
        :scroll="scroll"
        :pagination="false"
      >
        <template #columns>
          <a-table-column
            title="物料编码"
            :width="100"
            align="center"
            data-index="managementNumber"
          ></a-table-column>
          <a-table-column
            title="物料名称"
            :width="100"
            align="center"
            data-index="managementName"
          ></a-table-column>
          <a-table-column title="换算率" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input disabled v-model="record.dosage" /> </template
          ></a-table-column>
          <a-table-column title="规格型号" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input disabled v-model="record.spec" /> </template
          ></a-table-column>
          <a-table-column title="库存总量" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input disabled v-model="record.totalAmount" /> </template
          ></a-table-column>
          <a-table-column title="空闲数量" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input disabled v-model="record.freeAmount" /> </template
          ></a-table-column>
          <a-table-column title="安全库存量" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input disabled v-model="record.safetyAmount" /> </template
          ></a-table-column>
          <a-table-column title="推荐委外数量" :width="100" align="center"
            ><template #cell="{ record }">
              <a-input-number
                :min="1"
                v-model="record.amount"
                disabled
              /> </template
          ></a-table-column>
        </template>
      </a-table>
    </a-spin>
  </pageHeader>
</template>

<script setup lang="ts">
  import { reactive, watchEffect, ref } from 'vue';
  import {
    getOutsourcingSupplier,
    postOutsourcing,
  } from '@/api/produce-management/production-operation/index';
  import { getSupplierInfo } from '@/api/buy-management/supplier-management/supplier-primary-list/index';
  import { useRoute, useRouter } from 'vue-router';
  import { Message } from '@arco-design/web-vue';
  import dayjs from 'dayjs';

  const formRef = ref();
  let router = useRouter();
  let loading = ref(false);
  const form = reactive<any>({
    list: {
      name: '1',
      item: [],
      outsourcingType: 1, // 委外类型
      planAmount: 0,
      state: 1,
    },
  });
  const SupplierInfo = ref([]);

  let WorkOrderHerders = [
    { code: 'workCode', name: '工单编号' },
    { code: 'bomName', name: '制造BOM' },
    { code: 'materialName', name: '产品名称' },
    { code: 'materialNumber', name: '产品编号' },
    { code: 'materialSpec', name: '规格型号' },
    { code: 'materialUnit', name: '基本单位' },
    { code: 'customerName', name: '客户名称' },
    { name: '紧急等级' }, //emergencyLevel
    { name: '结束时间' }, //endDate
    { code: 'foundName', name: '创建人' },
    { name: '物料属性' }, //materialAttribute
    { code: 'orderNumber', name: '生产订单编号' },
    { code: 'plannerName', name: '负责人名称' },
    { name: '工艺路线' },
    // { code: 'salesName', name: '销售名称' },
    { name: '开始时间' }, //startDate
  ];
  const materialData = ref([]);

  const TreeData = (data: any, parentMultiplier: number) => {
    const currentMultiplier = parentMultiplier * data.dosage;
    if (!data.children) {
      return [{ ...data, dosage: currentMultiplier }];
    }
    const result: any = [];
    data.children.forEach((item: any) => {
      const childResult = TreeData(item, currentMultiplier);
      result.push(...childResult);
    });
    return result;
  };

  const loadTransferOutsourcingData = async () => {
    try {
      const transferData = JSON.parse(
        sessionStorage.getItem('TransferOutsourcing') as any
      );
      Object.assign(form.list, transferData);
      form.list.managementId = form.list.productId;
      form.list.produceOrderId = form.list.orderId;
      form.list.planId = form.list.id;
      form.list.state = 1;
      if (form.list.data) {
        form.list.planAmount += form.list.data.reduce(
          (acc, ele) => acc + ele.number,
          0
        );
      }
      const supplierInfo = await getSupplierInfo({ id: form.list.productId });
      SupplierInfo.value = supplierInfo;
    } catch (error) {
      console.error(error);
    }
  };
  loadTransferOutsourcingData();

  const EnableInventory = async (e) => {
    try {
      if (e === 1) {
        let newArr: any = [];
        const res = await getOutsourcingSupplier({ id: form.list.productId });
        form.list.item = TreeData(res, res.dosage);
        form.list.item.forEach((ele: any) => {
          const index = newArr.findIndex((i: any) => ele.bomName === i.bomName);
          if (index === -1) {
            newArr.push({ ...ele });
          } else {
            newArr[index].dosage += ele.dosage;
          }
        });
        form.list.item = newArr;
        if (form.list.amount) {
          form.list.item.forEach((item: any) => {
            item.amount = form.list.amount * item.dosage;
          });
        }
      } else {
        form.list.item = [];
      }
    } catch (err: unknown) {
      console.log(err);
    }
  };

  watchEffect(() => {
    if (form.list.unitPrice && form.list.amount) {
      form.list.totalPrice = form.list.unitPrice * form.list.amount;
    } else if (form.list.item.length) {
      form.list.item.forEach((item: any) => {
        item.amount = form.list.amount * item.dosage;
      });
    }
  });

  watchEffect(() => {
    if (form.list.item.length) {
      if (form.list.amount) {
        form.list.item.forEach((item: any) => {
          item.amount = form.list.amount * item.dosage;
        });
      }
    }
  });

  const handleOk = () => {
    formRef.value.validate(async (res) => {
      if (!res) {
        form.list.outsourcingDate = new Date(
          form.list.outsourcingDate
        ).toJSON();
        form.list.entryDate = new Date(form.list.entryDate).toJSON();
        form.list.item.forEach((item) => {
          if (item.totalAmount < item.safetyAmount || !item.totalAmount) {
            Message.warning(
              `${item.managementName}产品的总库存量已低至安全库存量，请及时补充`
            );
          }
        });
        await postOutsourcing({ ...form.list });
        router.push({ name: 'ProductOutsourcing' });
      }
    });
  };
</script>

<style scoped lang="less">
  .cantainer {
    padding: 20px;
    width: 100%;
  }
  .form {
    padding-left: 100px;
    padding-right: 100px;
  }
  .tab {
    border-left: 4px rgb(var(--arcoblue-6)) solid;
    padding-left: 20px;
    margin-bottom: 30px;
    font-size: 20px;
  }
  .orderBox {
    padding-left: 50px;
    // padding: 0px;
  }

  .box {
    padding-top: 10px;
    margin-top: 20px;
    border-top: 1px solid #e4e4e4;
    display: flex;
    justify-content: end;
    width: 100%;
  }
</style>
